<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 *  User Controller
 *
 * @package XGO CMS v2.0
 * @subpackage user
 * @author Manh Nguyen - 07/08/2012
 * @link http://sunsoft.vn
 */
class User extends CI_Controller {

    /**
     * Contrust class
     *
     * @access public
     */
    public function __construct() {
        parent::__construct();

		$this->load->library('smarty3', '', 'smarty');
        
        require_once(APPPATH . 'modules/backend/autoload.php');
        
        $this->load->library('login_manager');
        require_once(APPPATH . 'modules/backend/info.php');

        $this->login_manager->check_role('user');
        $this->load->language('backend');
        $this->smarty->assign('language', $this->lang);
        $this->smarty->assign('message', $this->session->flashdata('message'));
        $this->smarty->assign('error_message', $this->session->flashdata('error_message'));
    }

    /**
     * index function, show jquery grid
     *
     * @access public
     * @param null
     * @return void
     */
    function index() {
        $parameters = $this->uri->ruri_to_assoc();

        if (isset($parameters['id'])) {
            $id = intval($parameters['id']);
            if ($id > 0) {
                $this->session->set_userdata('search_id', $id);
            }
        }

        $css_files = array(base_url() . 'data/jscripts/jqgrid/css/ui.jqgrid.css');

        $js_files = array(
            base_url() . 'data/jscripts/jqgrid/i18n/grid.locale-vi.js',
            base_url() . 'data/jscripts/jqgrid/jquery.jqGrid.min.js'
        );

        require_once(APPPATH . 'modules/backend/history.php');

        $user = new User_model();

        //load parameters and initialize grid
        $jqgrid = array();

        $jqgrid['id'] = 'jqgrid';
        $jqgrid['pager'] = 'pagered';
        $jqgrid['caption'] = $user->localize_label('manager');
        $jqgrid['url_metadata'] = site_url($this->router->directory . 'user/jqgrid_jsoninit');
        $jqgrid['url_data'] = site_url($this->router->directory . 'user/jqgrid_jsondata');
        $jqgrid['url_create'] = site_url($this->router->directory . 'user/create');
        $jqgrid['url_edit'] = site_url($this->router->directory . 'user/edit');
        $jqgrid['url_delete'] = site_url($this->router->directory . 'user/delete');

        $this->smarty->assign('jqgrid', $jqgrid);

        $jqgrid_init = $this->smarty->get_contents('template/backend/js/jqgrid');
        $js_text = array($jqgrid_init);

        $this->smarty->assign('css_files', $css_files);
        $this->smarty->assign('js_files', $js_files);
        $this->smarty->assign('js_text', $js_text);
        $this->smarty->assign('title', $user->localize_label('manager'));

        // view
        $this->smarty->view('backend/user/jqgrid', 'grid');
        $this->smarty->display('template/backend/admin');
    }

    /**
     * Create user
     *
     * @access public
     */
    public function create() {

        $user = new User_model();
        $language = new Language_model();
        
        $this->smarty->assign('language', $language);
        $this->smarty->assign('user', $user);

        if ($this->input->server('REQUEST_METHOD') === 'GET') {
            $this->smarty->view('backend/user/edit', 'main_content');
            $this->smarty->display('template/backend/admin');
        } else {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('username', $user->localize_label('username'), 'trim|required|is_unique[users.username]|min_length[5]|max_length[150]');
            $this->form_validation->set_rules('password', $user->localize_label('password'), 'required|min_length[6]|matches[confirm_password]');
            $this->form_validation->set_rules('confirm_password', $user->localize_label('confirm_password'), 'required');
            $this->form_validation->set_rules('email', $user->localize_label('email'), 'required|valid_email');

            if ($this->form_validation->run() == TRUE) {
                $user = new User_model();
                $this->_save(site_url('auth/user'), $user);
            } else {
                $this->smarty->view('backend/user/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            }
        }
    }

    public function edit() {

        $user 		= new User_model();
        $language 	= new Language_model();        
        $this->smarty->assign('language', $language);
        $this->smarty->assign('user', $user);

        if ($this->input->server('REQUEST_METHOD') === 'GET') {
            $parameters = $this->uri->ruri_to_assoc(3);

            if (isset($parameters['id'])) {
                $id = intval($parameters['id']);
            } else {
                $id = 0;
            }

            $user->get_by_id($id);

            if ($user->exists()) {          
                $this->smarty->view('backend/user/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            } else {
                $this->session->set_flashdata('error_message', $this->lang->line('not_found') /* 'B�i vi?t n�y kh�ng t?n t?i xin vui l�ng ki?m tra l?i.' */);
                redirect(site_url('auth/user'));
            }
        } else {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email', $user->localize_label('email'), 'required|valid_email');

            $id = $this->input->post('id');
            $user->get_by_id($id);

            if ($this->form_validation->run() == TRUE) {
                $this->_save(site_url('auth/user/'), $user);
                //$user->save();
            } else {
                $this->smarty->assign('user', $user);
                $this->smarty->view('backend/user/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            }
        }
    }

    private function _save($uri, $user) {
        // Begin transaction
        $user->trans_begin();

        $this->load->helper('news');

        $user->firstname = $this->input->post('firstname');
        $user->lastname = $this->input->post('lastname');
        $user->gender = $this->input->post('gender');
        $user->email = $this->input->post('email');
        $user->phone = $this->input->post('phone');
        $user->image = $this->input->post('image');
        $user->address = $this->input->post('address');
        $user->active = $this->input->post('active');
        $user->group_id = $this->input->post('group_id');
        $user->language_id = $this->input->post('lang_id');

        $current_user = $this->login_manager->get_user();

        $now = date("Y:m:d H:i:s");

        if (!isset($user->id)) {
            //created
            $user->created = $now;
            $user->creator_id = $current_user->id;
            $user->username = $this->input->post('username');
            $user->password = $this->input->post('password');
            $user->confirm_password = $this->input->post('confirm_password');
        } else {
            //edit
            $user->updated = $now;
            $user->editor_id = $current_user->id;
        }

        $user->save();
        $exists = $user->exists();
        // Attempt to save user
        // Check status of transaction
        if ($user->trans_status() === FALSE) {
            // Transaction failed, rollback
            $user->trans_rollback();

            // Add error message
            $u->error_message('transaction', 'The transaction failed to save (insert)');
        } else {
            // Transaction successful, commit
            $user->trans_commit();

            if ($exists) {
                $this->session->set_flashdata('message', $user->localize_label('edit_success') /* '�� c?p nh?t du~ li�?u th�nh c�ng.' */);
            } else {
                $this->session->set_flashdata('message', $user->localize_label('create_success')/* '�� luu d? li?u th�nh c�ng.' */);
            }
            redirect($uri);
        }
        // Show all errors
        $error = $user->error->string;

        $this->session->set_flashdata('message', $error);
        redirect($uri);
    }

    /**
     * change password of user
     *
     * @access public
     * @param null
     * @return void
     */
    public function change_password() {

        $this->load->language('backend');

        $user = new User_model();
        $parameters = $this->uri->ruri_to_assoc(3);

        if (isset($parameters['id'])) {
            $id = intval($parameters['id']);
        } else {
            $id = $this->input->post('id');
        }

        $user->get_by_id($id);

        if ($user->exists()) {
            if ($this->input->server('REQUEST_METHOD') === 'POST') {
                $user->password = $this->input->post('password');
                $user->confirm_password = $this->input->post('confirm_password');
                $user->updated = date("Y:m:d H:i:s");
                if ($user->save()) {
                    $this->session->set_flashdata('message', $user->localize_label('updated_password'));
                    redirect($this->router->directory . 'user');
                } else {
                    $this->session->set_flashdata('message', $user->localize_label('error_confirm_password'));
                }
            }
        } else {
            $this->session->set_flashdata('message', $user->localize_label('error_username'));
            redirect($this->router->directory . 'user');
        }

        $this->smarty->assign('user', $user);

        // view
        $this->smarty->view('backend/user/change_password', 'main_content');
        $this->smarty->display('template/backend/admin');
    }

    /**
     * init function, get para for jquery grid via ajax
     * 
     * @access public
     * @param null
     * @return array in json encode
     */
    function jqgrid_jsoninit() {
        if (IS_AJAX) {
            $user = new User_model();
            $metadata = $user->jqgrid_metadata();
            echo json_encode($metadata);
        }
    }

    /**
     * data function, get data for jquery grid via ajax
     * 
     * @access public
     * @param null
     * @return array in json encode
     */
    function jqgrid_jsondata() {
        if (IS_AJAX) {
            $search = $this->input->post('_search');
            $filters = json_decode($this->input->post('filters'));
            $order = $this->input->post('sidx');
            $order_direct = $this->input->post('sord');
            $page = intval($this->input->post('page'));
            $num_per_page = intval($this->input->post('rows'));

            $relative_search = array(
                'group' => array(
                    'search' => 'id',
                    'include' => array('id', 'title')
                )
            );

            $this->load->helper('jqgrid');

            $user = jqgrid_search(new User_model(), $search, $filters, $order, $order_direct, $page, $num_per_page, $relative_search);

            $paged = $user->paged;
            $responce = new Stdclass();
            $responce->page = $paged->current_page; //curent page
            $responce->total = $paged->total_pages; //total page
            $responce->records = $paged->total_rows; //total record
            $i = 0;

            foreach ($user as $item) {
                $isLeaf = TRUE;
                $responce->rows[$i]['cell'] = array(
                    // Field
                    $item->id,
                    $item->username,
                    $item->firstname,
                    $item->lastname,
                    $user->validation['gender']['values'][$item->gender],
                    $item->email,
                    $item->phone,
                    $item->address,
                    $item->get_active(),
                    $item->group_title,
                    // Format
                    NULL,
                    NULL,
                    $isLeaf,
                    false
                );
                $i++;
            }
            echo json_encode($responce);
        }
    }

    /**
     * delete function, delete exists object
     * 
     * @access public
     * @param id of object in url
     * @return void
     */
    function delete() {

        $url = 'user';
        // Lay ID va kiem tra ID phai > 0
        $array_para = $this->uri->ruri_to_assoc();
        if (isset($array_para['id'])) {
            $ids = explode('-',$array_para['id']);
            foreach($ids as $value)
            {
                $id[] = intval($value);
            }
        } else {
            $id = 0;
        }
        if ($id <= 0) {
            //$this->session->set_flashdata('message', $this->lang->line('no_access_direct'));
            $this->session->set_flashdata('error_message', $this->lang->line('not_found'));
            redirect($this->router->directory . $url);
        }
        // Kiem tra su ton tai cua doi tuong
        foreach($id as $value){
        $user = new User_model();
        $user->where('id', $value);
        $user->get(1);
        if ($user->id <= 0) {
            //$this->session->set_flashdata('message', $this->lang->line('invalide_id'));
            $this->session->set_flashdata('error_message', $this->lang->line('not_found'));
            redirect($this->router->directory . $url);
        }
        /*
        // Kiem tra quyen xoa
        if (!$user->check_delete($this->login_manager->get_user())) {            
            $this->session->set_flashdata('message', $this->lang->line('no_access_right'));
            redirect($this->router->directory . $url);
        }*/
       
        // Thuc hien xoa va thong bao ket qua
        $text = $user->model . ' (' . $user->title . ')';
        $result = $user->delete();
        if ($result === TRUE) {
            $this->session->set_flashdata('message', $user->localize_label('delete_success'));
        } else {
            if ($result == -1) {
                $this->session->set_flashdata('message', $user->localize_label('delete_admin'));
            } elseif ($result == -2) {
                $this->session->set_flashdata('message', $user->localize_label('delete_news_first'));
            } else {
                $this->session->set_flashdata('message', $user->localize_label('delete_fail'));
            }
        }
        }
        redirect($this->router->directory . $url);
    }

}

/* End of file user.php */
/* Location: ./system/application/controllers/backend/user.php */